package com.hankol.community.viewmodel

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.lifecycle.MutableLiveData
import com.baselibrary.Constants
import com.baselibrary.MessageBus
import com.baselibrary.base.BasicListBean
import com.baselibrary.activity.BaseActivity
import com.baselibrary.base.mvvm.BaseViewModel
import com.baselibrary.bean.CommentEnum
import com.baselibrary.bean.ShareItemBean
import com.baselibrary.extension.checkNotNull
import com.baselibrary.utils.*
import com.baselibrary.view.share.SharePopupWindow
import com.okhttp.comment.CommentBean
import com.google.android.material.tabs.TabLayout
import com.hankol.community.R
import com.hankol.community.SelectFriendShareActivity
import com.hankol.community.ShareFriendActivity
import com.hankol.community.api.CommunityConstant
import com.hankol.community.arouter.CommunityHelp
import com.hankol.community.bean.*
import com.hankol.community.databinding.ActivityPulpitVideoBinding
import com.hankol.community.respository.CommunityRequestManager
import kotlin.math.roundToLong

/**
 * @author: 关忆北、
 * @date: 2022/4/25
 * @Des：
 */
class PulpitViewModel : BaseViewModel() {
    var unlockPulpitLD: MutableLiveData<Boolean> = MutableLiveData()
    var saveProgressLD: MutableLiveData<Boolean> = MutableLiveData()//视频进度保存
    var pulpitHomeLD: MutableLiveData<PulpitInfoBean> = MutableLiveData()
    var forumCourseLD: MutableLiveData<PulCourseBean> = MutableLiveData()
    var commentListLiveData: MutableLiveData<CommentBean.DataBean> = MutableLiveData()
    var pulpitListLD: MutableLiveData<BasicListBean<PulpitListBean>> = MutableLiveData()
    fun reqPulpitHome(pulpitId: Long) {
        CommunityRequestManager.getInstance().reqPulpitHome(pulpitId, pulpitHomeLD)
    }

    fun reqPulpitList(pulId: Long) {
        CommunityRequestManager.getInstance().reqPulpitList(pulId, pulpitListLD)
    }

    fun reqUnlockPulpit(activity: Activity, price: Long, pulpitId: Long) {

        PopUtils.showDialog(activity, "确认解锁该讲坛么？", "你将支付${price}酒币解锁该讲坛所有内容", object : PopUtils.ICallBack {
            override fun clickOk() {
                CommunityRequestManager.getInstance().reqUnlockPulpit(pulpitId, unlockPulpitLD)
            }

            override fun clickCancel() {}

        })
    }

    fun reqCommentList(pager: Int, pulVideoId: Long, topCommentId: Long) {
        CommunityRequestManager.getInstance().reqCommentList(commentListLiveData, pager, CommentEnum.COMMENT_FORUM_COURSE.commentType, pulVideoId, 0, topCommentId)
    }

    fun reqPulCourse(courseId: Long) {
        CommunityRequestManager.getInstance().reqPulCourse(courseId, forumCourseLD)
    }

    fun reqStatistics(courseId: Long) {
        CommunityRequestManager.getInstance().reqStatistics(courseId)
    }

    /**
     * @param offset 视频播放进度 秒
     * @param videoSaveProgress 学习进度
     */
    fun reqSaveProgress(fid: Long, offset: Long, videoSaveProgress: Long) {
        CommunityRequestManager.getInstance().reqSaveProgress(fid, offset, videoSaveProgress, saveProgressLD)
    }

    fun initTabView(context: Context, tabLayout: TabLayout, mTableName: MutableList<String>) {
        for (i in 0 until tabLayout.tabCount) {
            val tabAt: TabLayout.Tab? = tabLayout.getTabAt(i)
            tabAt?.customView = getTabView(context, i, mTableName)
        }
    }

    fun changeTabSelect(context: Context, tab: TabLayout.Tab, isSelect: Boolean) {
        val view = tab.customView ?: return
        val tvTab = view.findViewById<TextView>(R.id.tv_tab)
        if (isSelect) {
            tvTab.setTextColor(context.resources.getColor(R.color.color_333333))
            tvTab.paint.isFakeBoldText = true
        } else {
            tvTab.setTextColor(context.resources.getColor(R.color.color_999999))
            tvTab.paint.isFakeBoldText = false
        }
    }

    private fun getTabView(context: Context, position: Int, mTableName: MutableList<String>): View {
        val view: View = LayoutInflater.from(context).inflate(R.layout.topic_tab_item, null)
        val tvTab = view.findViewById<TextView>(R.id.tv_tab)
        if (0 == position) {
            tvTab.setTextColor(context.resources.getColor(R.color.color_333333))
            tvTab.paint.isFakeBoldText = true
        } else {
            tvTab.setTextColor(context.resources.getColor(R.color.color_999999))
            tvTab.paint.isFakeBoldText = false
        }
        tvTab.text = mTableName[position]
        return view
    }

    /**
     * 隐藏状态栏
     */
    fun hideNavigationBar(activity: Activity) {
        var uiFlags = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                or View.SYSTEM_UI_FLAG_FULLSCREEN)
        uiFlags = uiFlags or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
        activity.window.decorView.systemUiVisibility = uiFlags
    }

    /**
     * 显示状态栏
     */
    fun showNavigationBar(activity: Activity) {
        val uiFlags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
        activity.window.decorView.systemUiVisibility = uiFlags
    }

    fun initPlayerViewState(mDataBinding: ActivityPulpitVideoBinding) {
        mDataBinding.llPulVideoSpeed.visibility = View.GONE
        mDataBinding.ivPulVideoPlay.visibility = View.VISIBLE
        mDataBinding.ivPulVideoPlay.isSelected = false
        mDataBinding.sbPulVideoSpeed.max = 0
        mDataBinding.sbPulVideoSpeed.progress = 0
    }

    fun upBarHeight(v: View, context: Context) {
        val layoutParams: RelativeLayout.LayoutParams = v.layoutParams as RelativeLayout.LayoutParams
        layoutParams.height = CommonUtil.getStatusBarHeight(context)
        v.layoutParams = layoutParams
    }


    fun getHKVideoConfig(mDataBinding: ActivityPulpitVideoBinding, offset: Long): HKVideoBean {
        return HKVideoBean.HKVideoBuilder().setReStar(false).setBinding(mDataBinding).setIvPlayState(mDataBinding.ivPulVideoPlay).setPBar(mDataBinding.pbPulVideoLoading).setTvCurrentSpeed(mDataBinding.tvPulVideoSpeed).setTvTotalSpeed(mDataBinding.sbPulVideoTotalSpeed).setIvFullScreen(mDataBinding.ivPulVideoFullScreen).setSBar(mDataBinding.sbPulVideoSpeed).setSecond(CommunityConstant.STUDY_SECOND).setOffset(offset).setRlVideoFatherView(mDataBinding.rlVideoFatherView).builder()
    }

    fun showShare(data: ShowShare2Bean, activity: BaseActivity, communityHelp: CommunityHelp): SharePopupWindow? {
        val url: String = data.url
        val title = if (data.title.checkNotNull()) data.title else ""
        val des = if (data.content.checkNotNull()) data.content else ""
        val shareItem = ShareManager.showSharePopWindow(activity, url, data.cover, title, des, object : SharePopupWindow.OnShareClickListener {
            override fun onShareClick(type: Int) {
                EventBusUtils.sendNotify(MessageBus.msgId_share_success)
            }

            override fun onShareFriendClick(bean: ShareItemBean) {
                if (bean.userId == 0L) {//私信
                    val intent = Intent(activity, SelectFriendShareActivity::class.java)
                    intent.putExtra("friend", bean)
                    intent.putExtra("dynamic", showShare2Bean2SelectSendFriend2Bean(data))
                    activity.startActivity(intent)
                } else {
                    val intent = Intent(activity, ShareFriendActivity::class.java)
                    intent.putExtra("friend", bean)
                    intent.putExtra("dynamic", showShare2Bean2SelectSendFriend2Bean(data))
                    activity.startActivity(intent)
                }
            }
        })
        shareItem?.setShareItem(false, false, false);
        return shareItem
    }

    fun pulCourseBean2showShare(bean: PulCourseBean): ShowShare2Bean {
        return ShowShare2Bean().apply {
            id = bean.id
            uid = 0//讲坛没有用户ID
            isFans = 0
            headUrl = bean.lecturerIcon
            showType = Constants.DYNAMIC_TYPE_BEMA_VIDEO_DETAIL
            name = bean.lecturer
            cover = bean.cover
            title = bean.title
            content = bean.title
            pulpitId = bean.fid
            url = Constants.FORUM_VIDEO_SHARE_URL + bean.fid + "&cid=" + bean.id
        }
    }

    /**
     * 计算视频百分比
     */
    fun videoComputing(speedNum: Double, totalNum: Double): Long {
        try {
            if (speedNum == totalNum) return 100
            return ((speedNum / totalNum) * 100).roundToLong()
        } catch (num: NumberFormatException) {
            //防止异常情况
            return 0
        }
    }

    fun noticeCourseCollection(b: Boolean) {
        EventBusUtils.sendNotify(if (b) MessageBus.msgId_pulCourse_collection_true else MessageBus.msgId_pulCourse_collection_false)
    }

    fun noticePulCollection(b: Boolean) {
        EventBusUtils.sendNotify(if (b) MessageBus.msgId_pul_collection_true else MessageBus.msgId_pul_collection_false)
    }

    /**
     * 更新用户收藏头像列表
     */
    fun upUserIconList(userIconList: ArrayList<String>): ArrayList<String> {
        val newUserIconList: ArrayList<String> = arrayListOf()
        if (userIconList.size > 0) {
            newUserIconList.addAll(userIconList)
            if (userIconList.size >= 5) {
                newUserIconList.removeAt(newUserIconList.size - 1)
                newUserIconList.add(0, SpUtils.getInstance().loadUserBean.data.icon)
            } else {
                newUserIconList.add(0, SpUtils.getInstance().loadUserBean.data.icon)
            }
        } else {
            newUserIconList.add(SpUtils.getInstance().loadUserBean.data.icon)
        }
        return newUserIconList
    }

    /**
     * 判断是否有自己的头像
     */
    fun detOwnUserIconList(userIconList: ArrayList<String>): ArrayList<String> {
        userIconList.forEach {
            if (it == SpUtils.getInstance().loadUserBean.data.icon) {
                userIconList.remove(it)
                return userIconList
            }
        }
        return userIconList
    }

    fun upBottomNum(mDataBinding: ActivityPulpitVideoBinding, pulCourseBean: PulCourseBean?) {
        pulCourseBean?.let {
            mDataBinding.includePulVideoComment.tvShareCount.text = if (it.shareNum > 0) NumberUtils.formatBigNum(it.shareNum.toString()) else "分享"
            mDataBinding.includePulVideoComment.tvCommentConCount.text = if (it.favoriteNum > 0) NumberUtils.formatBigNum(it.favoriteNum.toString()) else "收藏"
            mDataBinding.includePulVideoComment.tvCommentComCount.text = if (it.commentNum > 0) NumberUtils.formatBigNum(it.commentNum.toString()) else "抢首评"
        }

    }

}